#!/usr/bin/env python
# -*- coding:utf-8 -*-


'''
@CreateTime: 2020/11/05 9:57
@Author : shouke
'''

import logging
import re
import os
logger = logging.getLogger(__name__)

class Utils:
    '''工具类'''

    @staticmethod
    def replace_variable(src_string, env, client_id):
        '''动态替换变量'''
        try:
            variable_list = re.findall('\${(.+?)}', src_string, re.DOTALL)
            variable_list = ['${%s}' % item for item in variable_list if not item.strip().startswith('_')] # 以 _ 打头的表示为函数

            for item in variable_list:
                variable = str(item.strip('${').strip('}').strip())
                if variable in env.runner.user_resource_dict[client_id]:
                    logger.debug('正在替换变量 %s 为 %s' % (item, env.runner.user_resource_dict[client_id][variable]) )
                    src_string = src_string.replace(item, env.runner.user_resource_dict[client_id][variable])
        except Exception as e:
            logger.error('替换动态变量出错：%s' % e)
        finally:
            return src_string


    @staticmethod
    def traverse_dir_files(dir_path, result=[]):
        '''递归遍历目录下的所有文件'''
        if not os.path.isdir(dir_path):
            return result
        for name in os.listdir(dir_path):
            full_path = os.path.join(dir_path, name)
            if os.path.isdir(full_path):
                Utils.traverse_dir_files(full_path)
            else:
                result.append(full_path)
        return result

    @staticmethod
    def get_scenario_config_files(dir_path):
        '''递归遍历目录下的所有文件'''

        result_list = []

        def get_config_files(dir_path, result_list):
            if not os.path.isdir(dir_path):
                return result_list
            for name in os.listdir(dir_path):
                full_path = os.path.join(dir_path, name)
                if os.path.isdir(full_path):
                    Utils.get_scenario_config_files(full_path)
                elif not name.startswith('_') and name.endswith('.py'):
                    result_list.append(full_path.replace('\\', '/'))
        get_config_files(dir_path, result_list)
        return result_list


